<template>
  <div class="img-loader">
    <div class="img-container">
      <item-img-loader :index="index" :img-url="url" v-for="(url,index) in picList" :key="index"
                       @onDeleteClick="deletePic"></item-img-loader>
      <btn-add-img :max-num="maxPicNum" @getPic="addPic"></btn-add-img>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import Public from '@/assets/js/public';
  import BtnAddImg from './BtnAddImg';
  import {Toast} from 'vant';
  import ItemImgLoader from './ItemImgLoader';
  import ImgCompressor from '../../util/ImgCompressor';

  export default {
    /** kebab-case */
    name: 'img-uploader',

    data() {
      return {
        picList: []
      };
    },
    /** 在声明 prop 的时候，其命名应该始终使用 camelCase，而在模板和 JSX 中应该始终使用 kebab-case。
     String/Number/Boolean/Function/Object/Array/Symbol */
    props: {
      maxPicNum: {
        required: true,
        type: Number,
        default: -1
      },
      toastTip: {
        required: true,
        type: String,
        default: 'maxPicNum=-1为无限选取'
      }
    },

    components: {ItemImgLoader, BtnAddImg},

    methods: {
      getIcon(icon) {
        return Public.ossImg + icon + '.svg';
      },
      addPic(img) {
        if (this.canPushMore()) {
          this.$emit('beforeLoad');
          ImgCompressor.compress(img, (imgEncode) => {
            this.picList.push(imgEncode);
            this.$emit('afterLoad');
          });
          // console.log('encode', imgEncode);
          // this.picList.push(img);
        } else {
          Toast(this.toastTip);
        }
        this.$emit('getPics', this.picList);
      },
      deletePic(index) {
        this.picList.splice(index, 1);
      },
      canPushMore() {
        if (this.maxPicNum < 0) {
          return true;
        } else {
          return this.picList.length < this.maxPicNum;
        }
      }
    },
    computed: {},
    watch: {
      // 监听具体数据变化，并做相应的处理
    }
  };
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
  @import "../../assets/stylus/main.styl";
  .flex-r
    flex-x()

  .flex-c
    flex-y()

  .center
    flex-center()

  .divider
    divider()

  .space
    space()

  .img-loader
    box-sizing border-box
    background white
    margin-bottom 25vw

  .title
    flex-center()
    justify-content flex-start
    word-main()
    height cell-height
    padding-left 10px

  .img-container
    flex-x()
    justify-content flex-start
    flex-wrap wrap
    box-sizing border-box
    width 100vw
    padding 0 3vw

  .wrapper
    width 23.5vw
    height 23.5vw
    padding 2vw
    box-sizing border-box
</style>
